package tv.dyndns.kishibe.client.game.shuffler;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import tv.dyndns.kishibe.client.packet.PacketProblem;

public class ShufflerTato implements Shuffleable {
	private static final int MAX_NUMBER_OF_CHOICES = 4;

	@Override
	public void shuffle(PacketProblem problem, int[] answerOrder, int[] choiceOrder) {
		Preconditions.checkNotNull(answerOrder);
		Preconditions.checkNotNull(choiceOrder);

		if (answerOrder.length < 1 || choiceOrder.length < 3) {
			problem.shuffledAnswers = null;
			problem.shuffledChoices = null;
			return;
		}

		Set<String> answers = ImmutableSet.copyOf(problem.getAnswerList());
		List<String> choices = Lists.newArrayList();

		// 正答を一つ追加する
		for (int i = 0; i < choiceOrder.length; ++i) {
			String choice = problem.choices[choiceOrder[i]];
			if (!answers.contains(choice)) {
				continue;
			}

			choices.add(choice);
			break;
		}

		// 選択肢を４つ選ぶ
		int numberOfChoices = Math.min(choiceOrder.length, MAX_NUMBER_OF_CHOICES);
		for (int i = 0; choices.size() < numberOfChoices; ++i) {
			String choice = problem.choices[choiceOrder[i]];
			if (choices.contains(choice)) {
				continue;
			}

			choices.add(choice);
		}

		// 4つの選択肢を並び替える
		List<Integer> secondOrder = Lists.newArrayList();
		for (int order : choiceOrder) {
			if (order < choices.size()) {
				secondOrder.add(order);
			}
		}

		problem.shuffledChoices = new String[numberOfChoices];
		for (int i = 0; i < choices.size(); ++i) {
			problem.shuffledChoices[i] = choices.get(secondOrder.get(i));
		}

		// 選択肢に対応した解答を作成する
		Set<String> remainedAnswers = Sets.newHashSet(answers);
		remainedAnswers.retainAll(Arrays.asList(problem.shuffledChoices));
		problem.shuffledAnswers = remainedAnswers.toArray(new String[0]);
	}
}
